#include "servermanager.h"
#include <QDebug>
serverManager::serverManager(QObject *parent) : QObject(parent)
{
    initServer();
}

serverManager::serverManager(QString ip, int port, QObject *parent):QObject(parent),ip(ip),port(port)
{
    initServer();
}


QString serverManager::getIp() const
{
    return ip;
}

void serverManager::setIp(const QString &value)
{
    ip = value;
}

int serverManager::getPort() const
{
    return port;
}

void serverManager::setPort(int value)
{
    port = value;
}


bool serverManager::start_listen() //开启监听
{

    if(ip.isEmpty() || port <=0 )
    {
        return false;
    }
    bool ret = server->listen(QHostAddress(ip),port);
    //qDebug()<<"开始监听";
    return ret;
}

void serverManager::initServer()
{
    server = new QTcpServer(this);
    connect(server,&QTcpServer::newConnection,this,&serverManager::onNewConnection);
}

void serverManager::onNewConnection()
{
    qDebug()<<"新连接";
    QTcpSocket * socket = server->nextPendingConnection();
    clientHandelr* handler = new clientHandelr(socket,this);
    handler->setServerManager(this);
    clients.insert(socket,handler);
    connect(handler,&clientHandelr::new_onlUser,this,&serverManager::onNewOnlUser);//在线列表错误获取
    connect(handler,&clientHandelr::onl_userOff,this,&serverManager::onOnlOff);
    connect(handler,&clientHandelr::client_upList,this,&serverManager::onclient_upList);
    connect(handler,&clientHandelr::singleMessage,this,&serverManager::on_singleMessage);
    emit new_client(handler);
}

void serverManager::onNewOnlUser(QString name,QTcpSocket* socket)
{
    this->onl_users.insert(name,socket);
    emit this->new_onlUser(name);
    //通知客户端用户更新(错误处理)
//    for(auto user=this->onl_users.begin();user!=this->onl_users.end();user++)
//    {
//        MessagePackage pack;
//        pack.setType("new_onl");
//        pack.setUserName(name);
//        MessagePackage::sendMessage(pack,user.value());
//    }
}

void serverManager::onOnlOff(QString name)
{
    this->onl_users.remove(name);
    emit this->onlUserOff(name);
}

void serverManager::onclient_upList(QTcpSocket* socket)
{
    for(auto user=this->onl_users.begin();user!=this->onl_users.end();user++)
    {
        MessagePackage pack;
        pack.setType("update");
        pack.setUserName(user.key());
//        qDebug()<<"列表 名单"<<pack.userName();
        MessagePackage::sendMessage(pack,socket);
    }
}

void serverManager::on_singleMessage(MessagePackage &pack)
{
    for(auto user=this->onl_users.begin();user!=this->onl_users.end();user++)
    {
        if(user.key()==pack.recvName())
        {
            MessagePackage::sendMessage(pack,user.value());
        }
    }
}
// 新增方法实现
bool serverManager::isUserOnline(const QString& username) const {
    return onl_users.contains(username);
}

QTcpSocket* serverManager::getUserSocket(const QString& username) const {
    return onl_users.value(username, nullptr);
}
